import { Hono } from "hono";
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod'
import activeClients from '../utils/activeClients.ts';
import { getConnInfo } from 'hono/deno'
import saveFile from "../utils/saveFile.ts";
import { encodeFileName } from "../utils/util.ts";



const setServerRoute = (app: Hono) => {
    const api = app.basePath('/api')
    api.post('/sendFile', zValidator(
        'form',
        z.discriminatedUnion('type', [
            z.object({
                target: z.string(),
                type: z.literal('file'),
                file: z.instanceof(File),
                text: z.never().optional(), // 禁止 text 字段
            }),
            z.object({
                target: z.string(),
                type: z.literal('text'),
                text: z.string(),
                file: z.never().optional(), // 禁止 file 字段
            }),
        ])
    ), (c) => {
        const validated = c.req.valid('form');
        const curIp = getConnInfo(c).remote.address;
        if(validated.type === 'file'){
            saveFile.addFile(validated.target, validated.file, curIp!);
        }else{
            saveFile.addTextFile(validated.target, validated.text, curIp!);
        }
        return c.json({ success: true, message: '发送成功' });
    })

    api.get('/ips', (c) => {
        const curIp = getConnInfo(c).remote.address;
        activeClients.addClient(curIp!);
        const ips = activeClients.getActiveClients(curIp!) || [];
        return c.json({ success: true, message: '获取IP成功', ips });
    })

    api.get('/files', (c) => {
        const curIp = getConnInfo(c).remote.address;
        const files = saveFile.getFiles(curIp!);
        return c.json({ success: true, message: '获取文件成功', files });
    })

    api.get('/downloadFile', zValidator(
        'query',
        z.object({
            fileName: z.string(),
        })
    ), async (c) => {
        // const body = await c.req.json()
        const fileName = c.req.valid('query').fileName;
        const curIp = getConnInfo(c).remote.address;
        
        const fileContent = await saveFile.downloadFile(curIp!, fileName);
        return c.body(fileContent, 200, {
            'Content-Type': 'application/octet-stream',
            'Content-Disposition': encodeFileName(fileName),
        });
    })
}


export default setServerRoute;